package BandB.Tool.GPhoneManager.AppManager.AppResore;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.LinkedList;
import BandB.Tool.GPhoneManager.AppManager.Settings;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;
import android.util.Log;

public class FileManager {

	private static FileFoundListener mFileFoundListener;

	public static void setFileFoundListener(FileFoundListener listener) {
		mFileFoundListener = listener;
	}

	private static final String TAG = FileManager.class.getSimpleName();

	public static boolean backupOneApkFile(ResolveInfo oneInfo,
			PackageManager pm, boolean backupDifferentVersion, String path) {
		String packageName = oneInfo.activityInfo.packageName;
		String fromPath = oneInfo.activityInfo.applicationInfo.sourceDir;
		String toPath;
		try {
			StringBuffer sb;
			if (backupDifferentVersion) {
				String versionName = pm.getPackageInfo(packageName, 0).versionName;
				if (TextUtils.isEmpty(versionName)) {
					versionName = "";
				}
				sb = new StringBuffer(100).append(Settings.APK_BACKUP_ROOT)
						.append(path).append(packageName).append(versionName)
						.append(".apk");
				toPath = sb.toString();
				return copyFile(fromPath, toPath);
			} else {
				sb = new StringBuffer(100).append(Settings.APK_BACKUP_ROOT)
						.append(path).append(packageName).append(".apk");
				toPath = sb.toString();
				return copyFile(fromPath, toPath);
			}

		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			Log.e(TAG, e.getMessage());
			return false;
		}
	}

	public static boolean backupOneApkFile(PackageInfo oneInfo,
			PackageManager pm, boolean backupDifferentVersion, String path) {
		ApplicationInfo applicationInfo = oneInfo.applicationInfo;
		String packageName = applicationInfo.packageName;
		String fromPath = applicationInfo.sourceDir;
		String toPath;
		try {
			StringBuffer sb;
			if (backupDifferentVersion) {
				String versionName = pm.getPackageInfo(packageName, 0).versionName;
				if (TextUtils.isEmpty(versionName)) {
					versionName = "";
				}
				sb = new StringBuffer(100).append(Settings.APK_BACKUP_ROOT)
						.append(path).append(packageName).append(versionName)
						.append(".apk");
				toPath = sb.toString();
				return copyFile(fromPath, toPath);
			} else {
				sb = new StringBuffer(100).append(Settings.APK_BACKUP_ROOT)
						.append(path).append(packageName).append(".apk");
				toPath = sb.toString();
				return copyFile(fromPath, toPath);
			}

		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			Log.e(TAG, e.getMessage());
			return false;
		}
	}

	public static boolean isApkFile(File file) {
		boolean isApkFile = false;
		String fileName = file.getName();
		// Log.e("BackManager", "file name: " + fileName);
		try {
			String fileSuffix = fileName.substring(fileName.lastIndexOf("."),
					fileName.length());
			// Log.i(TAG, "current file suffix=" + fileSuffix);
			if (fileSuffix.toLowerCase().equalsIgnoreCase(".apk")) {
				isApkFile = true;
			}
		} catch (Exception e) {
			return false;
		}

		return isApkFile;
	}

	/**
	 * Get all apk files in the specified path.
	 * 
	 * @param filePath
	 *            This is probably referenced as "/sdcard/"
	 * @return a file list
	 */
	public static LinkedList<File> getAllAppFile(String filePath) {
		LinkedList<File> fileList1 = new LinkedList<File>();

		LinkedList<File> list = new LinkedList<File>();
		File file[] = new File(filePath).listFiles();
		for (int i = 0; i < file.length; i++) {
			if (file[i].isDirectory()) {
				list.add(file[i]);
			} else {
				if (file[i].isFile() && isApkFile(file[i])) {
					fileList1.add(file[i]);
					mFileFoundListener.onFileFound(file[i]);
				}
			}
		}
		File tmp;
		while (!list.isEmpty()) {
			tmp = list.removeFirst();
			if (tmp.isDirectory()) {
				file = tmp.listFiles();
				if (file == null) {
					continue;
				}
				for (int i = 0; i < file.length; i++) {
					if (file[i].isDirectory()) {
						list.add(file[i]);
					} else {
						if (file[i].isFile() && isApkFile(file[i])) {
							fileList1.add(file[i]);
							mFileFoundListener.onFileFound(file[i]);
						}
					}
				}
			}
		}
		return fileList1;
	}

	private static boolean copyFile(File filefrom, File fileto, boolean rewrite) {
		if (!filefrom.exists()) {
			Log.i(TAG, "filefrom not exist");
			return false;
		}
		if (!filefrom.isFile()) {
			Log.i(TAG, "filefrom is not file ");
			return false;
		}
		if (!filefrom.canRead()) {
			Log.i(TAG, "filefrom can't read");
			return false;
		}
		if (!fileto.getParentFile().exists()) {
			Log.i(TAG, "fileto's parent not exist");
			if (fileto.getParentFile().mkdirs()) {
				Log.i(TAG, "succeed create parent dir");
			}
		}
		if (fileto.exists() && rewrite) {
			Log.i(TAG, "fileto is exist ,need to rewrite");
			final boolean deleteSuccess = fileto.delete();
			if (deleteSuccess) {
				Log.i(TAG, "delete success");
			}
		}

		try {
			final FileInputStream fosfrom = new FileInputStream(filefrom);
			final FileOutputStream fosto = new FileOutputStream(fileto);
			final byte bt[] = new byte[1024];
			int c;
			while ((c = fosfrom.read(bt)) > 0) {
				fosto.write(bt, 0, c);
			}
			fosfrom.close();
			fosto.close();
			return true;
		} catch (Exception ex) {
			Log.i(TAG, ex.getMessage());
			return false;
		}

	}

	private static boolean copyFile(String from, String to) {
		File filefrom = new File(from);
		File fileto = new File(to);
		return copyFile(filefrom, fileto, true);
	}
}
